﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FDSimpleModelGenerator.Entities;
using FDSimpleModelGenerator.IServices;
using FDSimpleModelGenerator.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace FDSimpleModelGenerator.Pages
{
    public class UploadModel : PageModel
    {
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly string TemplatePath;
        private readonly IClassTemplateService _classTemplateService;
        private readonly IClassTemplateCategoryService _classTemplateCategoryService;

        public UploadModel(IWebHostEnvironment hostingEnvironment, IClassTemplateService classTemplateService, IClassTemplateCategoryService classTemplateCategoryService)
        {
            _classTemplateCategoryService = classTemplateCategoryService;
            _classTemplateService = classTemplateService;
            _hostingEnvironment = hostingEnvironment;

            TemplatePath = Path.Combine(_hostingEnvironment.WebRootPath, "Templates");

            //InitData();
        }

        /// <summary>
        /// 初始化基础数据
        /// </summary>
        private void InitData()
        {
            _classTemplateCategoryService.Add(new ClassTemplateCategory { Name = "C#类模板", Description = "C#模板分类" });
            _classTemplateCategoryService.Add(new ClassTemplateCategory { Name = "Java类模板", Description = "Java模板分类" });
            _classTemplateService.Add(new ClassTemplate
            { Category = 1, Description = "C#模型类模板", FileName = "CSClass.fdtpl", Name = "CSClass" });
            _classTemplateService.Add(new ClassTemplate
            { Category = 2, Description = "Java模型类模板", FileName = "JavaClass.fdtpl", Name = "JavaClass" });
        }

        public void OnGet()
        {

        }

        public async Task<IActionResult> OnPostServer()
        {
            var files = Request.Form.Files;
            return await Task.Run(() =>
            {
                StringBuilder sb = new StringBuilder();
                var path = string.Empty;
                var succCount = 0;
                var upFiles = new List<string>();
                foreach (IFormFile file in files)
                {
                    var fileName = file.FileName;
                    path = Path.Combine(TemplatePath, fileName);
                    var ext = Path.GetExtension(fileName);
                    if (!".fdtpl".Equals(ext, StringComparison.OrdinalIgnoreCase))
                    {
                        sb.Append($"模板文件{fileName}非模板文件，不允许上传。");
                        continue;
                    }
                    if (System.IO.File.Exists(path))
                    {
                        sb.Append($"模板文件{fileName}已存在，不允许覆盖。");
                        continue;
                    }

                    using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        file.CopyTo(fs);
                    }
                    succCount++;
                    upFiles.Add(fileName);
                    sb.Append($"save {file.Name}={file.FileName},");
                }

                if (succCount == files.Count)
                {
                    return new JsonResult(ApiResult.Success(upFiles, sb.ToString()));
                }
                return new JsonResult(ApiResult.Failure(ApiResultCode.Failure, sb.ToString()));
            });
        }
    }
}